<template>
	<view class="add-reminder">
		<view class="form-header">
			<text class="main-title">{{ isEditMode ? '编辑提醒' : '添加提醒' }}</text>
			<text class="sub-title">设置健康提醒，关注您的健康</text>
		</view>

		<form @submit="submitForm">
			<view class="form-group">
				<view class="form-item">
					<text class="label">提醒类型</text>
					<view class="type-selector">
						<view 
							v-for="(type, index) in typeOptions" 
							:key="index"
							class="type-item"
							:class="{ active: formData.type === type.value }"
							@tap="formData.type = type.value"
						>
							<text class="type-icon iconfont" :class="type.icon"></text>
							<text class="type-name">{{ type.label }}</text>
						</view>
					</view>
				</view>
				
				<view class="form-item">
					<text class="label required">提醒标题</text>
					<input 
						class="input" 
						type="text" 
						v-model="formData.title"
						placeholder="请输入提醒标题" 
						maxlength="30"
					/>
					<text class="error" v-if="errors.title">{{ errors.title }}</text>
				</view>
				
				<view class="form-item">
					<text class="label">提醒描述</text>
					<textarea 
						class="textarea" 
						v-model="formData.desc" 
						placeholder="请输入提醒描述（选填）" 
						maxlength="100"
					></textarea>
				</view>
				
				<view class="form-item">
					<text class="label required">提醒时间</text>
					<picker
						mode="time"
						:value="formData.time"
						@change="formData.time = $event.detail.value"
						class="picker"
					>
						<view class="picker-text">
							<text>{{ formData.time || '请选择时间' }}</text>
							<text class="iconfont icon-down"></text>
						</view>
					</picker>
					<text class="error" v-if="errors.time">{{ errors.time }}</text>
				</view>
				
				<view class="form-item">
					<text class="label">重复方式</text>
					<picker
						mode="selector"
						:range="repeatOptions"
						:value="repeatIndex"
						@change="handleRepeatChange"
						class="picker"
					>
						<view class="picker-text">
							<text>{{ repeatOptions[repeatIndex] }}</text>
							<text class="iconfont icon-down"></text>
						</view>
					</picker>
				</view>
				
				<view class="form-item" v-if="formData.repeat === 'weekly'">
					<text class="label">重复日期</text>
					<view class="week-selector">
						<view 
							v-for="(day, index) in weekDays" 
							:key="index"
							class="week-item"
							:class="{ active: selectedDays.includes(index + 1) }"
							@tap="toggleWeekDay(index + 1)"
						>
							{{ day }}
						</view>
					</view>
					<text class="error" v-if="errors.repeatDays">{{ errors.repeatDays }}</text>
				</view>
				
				<view class="form-item" v-if="formData.repeat === 'once'">
					<text class="label">日期</text>
					<picker
						mode="date"
						:value="formData.date"
						start="2023-01-01"
						end="2030-12-31"
						@change="formData.date = $event.detail.value"
						class="picker"
					>
						<view class="picker-text">
							<text>{{ formData.date || '请选择日期' }}</text>
							<text class="iconfont icon-down"></text>
						</view>
					</picker>
					<text class="error" v-if="errors.date">{{ errors.date }}</text>
				</view>
			</view>
			
			<view class="form-footer">
				<button class="btn-cancel" @tap="goBack">取消</button>
				<button class="btn-submit" form-type="submit">{{ isEditMode ? '更新' : '保存' }}</button>
			</view>
		</form>
	</view>
</template>

<script>
	import { addReminder, getReminderDetail, updateReminder, initReminderData } from '@/common/api/reminder.js'
	
	export default {
		data() {
			return {
				reminderId: null,
				isEditMode: false,
				formData: {
					title: '',
					desc: '',
					time: '',
					repeat: 'daily',
					repeatDays: [],
					date: '',
					type: 'medicine',
					active: true
				},
				rules: {
					type: {
						rules: [{
							required: true,
							errorMessage: '请选择提醒类型'
						}]
					},
					title: {
						rules: [{
							required: true,
							errorMessage: '请输入提醒标题'
						}]
					},
					time: {
						rules: [{
							required: true,
							errorMessage: '请选择提醒时间'
						}]
					},
					repeat: {
						rules: [{
							required: true,
							errorMessage: '请选择重复规则'
						}]
					},
					repeatDays: {
						rules: [{
							validator: (rule, value, data, callback) => {
								if (data.repeat === 'weekly' && (!value || value.length === 0)) {
									callback('请至少选择一天');
								}
								return true;
							}
						}]
					}
				},
				typeOptions: [
					{ label: '服药', value: 'medicine', icon: 'icon-medicine' },
					{ label: '血糖检测', value: 'bloodSugar', icon: 'icon-blood' },
					{ label: '运动', value: 'exercise', icon: 'icon-exercise' },
					{ label: '饮食', value: 'diet', icon: 'icon-diet' },
					{ label: '其他', value: 'other', icon: 'icon-other' }
				],
				repeatOptions: ['每天', '每周', '不重复'],
				repeatIndex: 0,
				weekDays: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
				errors: {
					title: '',
					time: '',
					repeatDays: '',
					date: ''
				},
				selectedDays: []
			}
		},
		onLoad(options) {
			// 确保本地数据已初始化
			initReminderData()
			
			// 设置当前日期和时间（用于添加模式）
			const today = new Date()
			const year = today.getFullYear()
			const month = String(today.getMonth() + 1).padStart(2, '0')
			const day = String(today.getDate()).padStart(2, '0')
			this.formData.date = `${year}-${month}-${day}`
			
			const hour = String(today.getHours()).padStart(2, '0')
			const minute = String(today.getMinutes()).padStart(2, '0')
			this.formData.time = `${hour}:${minute}`
			
			// 检查是否为编辑模式
			if (options.mode === 'edit' && options.id) {
				this.isEditMode = true
				this.reminderId = options.id
				this.loadReminderDetail()
			}
		},
		methods: {
			// 加载提醒详情（编辑模式）
			async loadReminderDetail() {
				uni.showLoading({
					title: '加载中...'
				})
				
				try {
					const res = await getReminderDetail(this.reminderId)
					
					if (res.code === 0 && res.data) {
						const reminder = res.data
						
						// 更新表单数据
						this.formData = {
							type: reminder.type,
							title: reminder.title,
							time: reminder.time,
							repeat: reminder.repeat,
							desc: reminder.desc || '',
							active: reminder.active
						}
						
						// 设置重复类型索引
						if (reminder.repeat === 'daily') {
							this.repeatIndex = 0
						} else if (reminder.repeat === 'weekly') {
							this.repeatIndex = 1
							this.selectedDays = [...reminder.repeatDays]
							this.formData.repeatDays = [...reminder.repeatDays]
						} else if (reminder.repeat === 'once') {
							this.repeatIndex = 2
							this.formData.date = reminder.date
						}
					} else {
						throw new Error(res.message || '提醒不存在')
					}
				} catch (e) {
					console.error('获取提醒详情失败:', e)
					uni.showToast({
						title: '获取提醒详情失败',
						icon: 'none'
					})
					
					setTimeout(() => {
						uni.navigateBack()
					}, 1500)
				} finally {
					uni.hideLoading()
				}
			},
			handleRepeatChange(e) {
				const index = e.detail.value
				this.repeatIndex = index
				
				switch(index) {
					case 0:
						this.formData.repeat = 'daily'
						break
					case 1:
						this.formData.repeat = 'weekly'
						if (this.selectedDays.length === 0) {
							this.selectedDays = [1, 2, 3, 4, 5]
						}
						this.formData.repeatDays = [...this.selectedDays]
						break
					case 2:
						this.formData.repeat = 'once'
						break
				}
			},
			
			toggleWeekDay(day) {
				const index = this.selectedDays.indexOf(day)
				if (index === -1) {
					this.selectedDays.push(day)
				} else {
					this.selectedDays.splice(index, 1)
				}
				this.formData.repeatDays = [...this.selectedDays]
			},
			
			goBack() {
				uni.navigateBack()
			},
			
			validateForm() {
				this.errors = {
					title: '',
					time: '',
					repeatDays: '',
					date: ''
				}
				
				let isValid = true
				
				if (!this.formData.title.trim()) {
					this.errors.title = '请输入提醒标题'
					isValid = false
				}
				
				if (!this.formData.time) {
					this.errors.time = '请选择提醒时间'
					isValid = false
				}
				
				if (this.formData.repeat === 'weekly' && this.selectedDays.length === 0) {
					this.errors.repeatDays = '请至少选择一天'
					isValid = false
				}
				
				if (this.formData.repeat === 'once' && !this.formData.date) {
					this.errors.date = '请选择日期'
					isValid = false
				}
				
				return isValid
			},
			
			async submitForm() {
				if (!this.validateForm()) {
					return
				}
				
				uni.showLoading({
					title: this.isEditMode ? '更新中...' : '保存中...'
				})
				
				try {
					const reminderData = {
						...this.formData
					}
					
					if (reminderData.repeat === 'daily') {
						delete reminderData.repeatDays
						delete reminderData.date
					} else if (reminderData.repeat === 'weekly') {
						if (reminderData.repeatDays.length === 0) {
							uni.hideLoading()
							uni.showToast({
								title: '请至少选择一天',
								icon: 'none'
							})
							return
						}
						delete reminderData.date
					} else if (reminderData.repeat === 'once') {
						if (!reminderData.date) {
							uni.hideLoading()
							uni.showToast({
								title: '请选择日期',
								icon: 'none'
							})
							return
						}
						delete reminderData.repeatDays
					}
					
					if (reminderData.repeat === 'daily') {
						reminderData.repeatText = '每天'
					} else if (reminderData.repeat === 'weekly') {
						const selectedDayNames = reminderData.repeatDays.map(day => this.weekDays[day - 1]).join('、')
						reminderData.repeatText = `每周 ${selectedDayNames}`
					} else {
						reminderData.repeatText = reminderData.date
					}
					
					let result
					
					if (this.isEditMode) {
						// 编辑模式：更新现有提醒
						result = await updateReminder(this.reminderId, reminderData)
					} else {
						// 添加模式：创建新提醒
						result = await addReminder(reminderData)
					}
					
					if (result.code === 0) {
						uni.hideLoading()
						uni.showToast({
							title: this.isEditMode ? '更新成功' : '添加成功',
							icon: 'success'
						})
						
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						throw new Error(result.message || (this.isEditMode ? '更新失败' : '添加失败'))
					}
				} catch (error) {
					console.error(this.isEditMode ? '更新提醒失败:' : '添加提醒失败:', error)
					uni.hideLoading()
					uni.showToast({
						title: typeof error === 'string' ? error : (this.isEditMode ? '更新失败' : '保存失败'),
						icon: 'none'
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	.add-reminder {
		padding: 30rpx;
		background-color: #f5f7fa;
		min-height: 100vh;
		
		.form-header {
			text-align: center;
			margin-bottom: 40rpx;
			
			.main-title {
				font-size: 44rpx;
				font-weight: bold;
				margin-bottom: 10rpx;
				color: #333;
			}
			
			.sub-title {
				font-size: 28rpx;
				color: #666;
			}
		}
		
		.form-group {
			background-color: #fff;
			border-radius: 16rpx;
			padding: 30rpx;
			box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.08);
			margin-bottom: 40rpx;
			
			.form-item {
				margin-bottom: 30rpx;
				
				&:last-child {
					margin-bottom: 0;
				}
				
				.label {
					display: block;
					font-size: 28rpx;
					font-weight: bold;
					margin-bottom: 16rpx;
					color: #333;
					
					&.required:after {
						content: '*';
						color: #ff6b6b;
						margin-left: 6rpx;
					}
				}
				
				.input, .textarea {
					width: 100%;
					height: 80rpx;
					padding: 0 20rpx;
					background-color: #f9f9f9;
					border: 1px solid #f0f0f0;
					border-radius: 12rpx;
					display: flex;
					align-items: center;
					font-size: 28rpx;
					color: #333;
					box-sizing: border-box;
				}
				
				.textarea {
					height: 160rpx;
					padding: 20rpx;
					line-height: 1.5;
				}
				
				.picker {
					width: 100%;
					
					.picker-text {
						height: 80rpx;
						padding: 0 20rpx;
						background-color: #f9f9f9;
						border: 1px solid #f0f0f0;
						border-radius: 12rpx;
						display: flex;
						justify-content: space-between;
						align-items: center;
						font-size: 28rpx;
						color: #333;
					}
				}
				
				.type-selector {
					display: flex;
					flex-wrap: wrap;
					margin: 0 -10rpx;
					
					.type-item {
						width: calc(33.33% - 20rpx);
						height: 120rpx;
						background-color: #f9f9f9;
						border: 1px solid #f0f0f0;
						color: #666;
						border-radius: 12rpx;
						margin: 10rpx;
						display: flex;
						flex-direction: column;
						align-items: center;
						justify-content: center;
						transition: all 0.3s ease;
						
						.type-icon {
							font-size: 40rpx;
							margin-bottom: 12rpx;
						}
						
						.type-name {
							font-size: 26rpx;
						}
						
						&.active {
							background: linear-gradient(135deg, #8cc9a1 0%, #5daa7f 100%);
							color: #fff;
							border-color: transparent;
							box-shadow: 0 8rpx 16rpx rgba(140, 201, 161, 0.3);
							transform: translateY(-2rpx);
						}
					}
				}
				
				.week-selector {
					display: flex;
					flex-wrap: wrap;
					margin: 0 -10rpx;
					
					.week-item {
						width: calc(14.28% - 20rpx);
						height: 80rpx;
						background-color: #f9f9f9;
						border: 1px solid #f0f0f0;
						color: #666;
						border-radius: 12rpx;
						margin: 10rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						font-size: 26rpx;
						transition: all 0.3s ease;
						
						&.active {
							background: linear-gradient(135deg, #8cc9a1 0%, #5daa7f 100%);
							color: #fff;
							border-color: transparent;
							box-shadow: 0 4rpx 12rpx rgba(140, 201, 161, 0.3);
							transform: translateY(-2rpx);
						}
					}
				}
				
				.error {
					display: block;
					font-size: 24rpx;
					color: #ff6b6b;
					margin-top: 10rpx;
				}
			}
		}
		
		.form-footer {
			display: flex;
			margin-top: 60rpx;
			padding: 0 20rpx;
			
			.btn-cancel, .btn-submit {
				flex: 1;
				height: 100rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				border-radius: 50rpx;
				font-size: 32rpx;
				transition: all 0.3s ease;
				border: none;
			}
			
			.btn-cancel {
				background-color: #f9f9f9;
				color: #666;
				margin-right: 30rpx;
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
				
				&:active {
					background-color: #f0f0f0;
					transform: translateY(2rpx);
				}
			}
			
			.btn-submit {
				background: linear-gradient(135deg, #8cc9a1 0%, #5daa7f 100%);
				color: #fff;
				box-shadow: 0 8rpx 20rpx rgba(140, 201, 161, 0.3);
				
				&:active {
					transform: translateY(4rpx);
					box-shadow: 0 4rpx 8rpx rgba(140, 201, 161, 0.3);
				}
			}
		}
	}
</style> 